package com.crm.system.controller.systemManager;

import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.model.entity.cluePoolManager.ClueContact;
import com.crm.model.entity.customerManager.SingleProductCustomerContact;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.systemManager.CallManagerQO;
import com.crm.model.vo.contactManager.ContactInformationVO;
import com.crm.model.vo.systemManager.CallManagerVO;
import com.crm.system.service.cluePoolManager.ClueContactService;
import com.crm.system.service.contactManager.ContactInformationService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.customerManager.SingleProductCustomerService;
import com.crm.system.service.systemManager.CallManagerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author renshaorong
 * @Date 2021/4/20
 */
@RestController
@RequestMapping("/systemManager/callManager")
@Slf4j
public class CallManagerController {
    @Autowired
    private CallManagerService callManagerService;

    @Autowired
    private ContactService contactService;

    @Autowired
    private SingleProductCustomerService singleProductCustomerService;

    @Autowired
    private ContactInformationService contactInformationService;

    @Autowired
    private ClueContactService clueContactService;

    /**
     * 根据当前登陆用户获取该用户权限下的呼叫信息
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @param callManagerQO
     * @return
     */
    @GetMapping("/getCallListsByUser")
    public DataResponse getCallListsByUser(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                           @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                           @RequestParam(value = "sortName", required = false) String sortName,//排序列名字
                                           @RequestParam(value = "sortOrder", required = false) String sortOrder,//排序规则(asc/desc)
                                           CallManagerQO callManagerQO//查询条件
                                           ){
        DhPageInfo<CallManagerVO> callLists = callManagerService.getCallListsByUser(pageIndex, pageSize, sortName, sortOrder,callManagerQO);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),callLists);
    }

    /**
     * 保存绑定信息
     * @param callManagerQO
     * @return
     */
    @PostMapping("/saveBindUser")
    public DataResponse saveBindUser(CallManagerQO callManagerQO){
        return callManagerService.saveBindUser(callManagerQO) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 解绑
     * @param callId
     * @return
     */
    @PostMapping("/cleanUserAccountId")
    public DataResponse cleanUserAccountId(@RequestParam("callId") String callId){
        return callManagerService.cleanUserAccountId(callId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 禁用
     * @param callId
     * @return
     */
    @PostMapping("disableByCallId")
    public DataResponse disableByCallId(@RequestParam("callId") String callId){
        return callManagerService.disableByCallId(callId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }
    /**
     * 可用
     * @param callId
     * @return
     */
    @PostMapping("availableByCallId")
    public DataResponse availableByCallId(@RequestParam("callId") String callId){
        return callManagerService.availableByCallId(callId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 获取呼叫信息列表，用于下拉框
     * @param request
     * @return
     */
    @GetMapping("/getCallListsByUserList")
    public DataResponse getCallListsByUserList(HttpServletRequest request, @RequestParam Short type, @RequestParam String accountId) {
        List<CallManagerVO> callManagers = callManagerService.getCallListsByUserList(type,accountId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), callManagers);
    }

    /**
     * 账号管理页面绑定号码
     * @param callManagerQO
     * @return
     */
    @PostMapping("bindCallId")
    public DataResponse bindCallId(CallManagerQO callManagerQO){
        return callManagerService.bindCallId(callManagerQO) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 批量禁用
     * @Date 2021/4/22
     * @param callIds
     * @return
     */
    @PostMapping("batchDisable")
    public DataResponse batchDisable(@RequestBody List<String> callIds){
        return callManagerService.batchDisable(callIds) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 拨打电话-线路切换获取随机号码
     * @Author pym
     * @Date  2021/5/26 8:35
     * @param request
     * @param type 号码类型 0、中继号 1、本地号 2、全国号
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @GetMapping("/getRandomTelephoneNumber")
    public DataResponse getRandomTelephoneNumber(HttpServletRequest request, @RequestParam String type) {
        String randomTelephoneNumber = callManagerService.getRandomTelephoneNumber(type);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), randomTelephoneNumber);
    }

    /**
     * 查询是否存在联系人
     * @Author pym
     * @Date  2021/6/11 15:39
     * @param contactInformation 联系电话
     * @param followSource 跟进来源：0-线索跟进；1-客户跟进；2-单品客户跟进;
     * @param callId 单品客户Id/线索Id
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/isContactExist")
    public DataResponse isContactExist(@RequestParam String contactInformation, @RequestParam(required = false) String followSource,
                                       @RequestParam(required = false) String callId) {
        try {
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            String accountId = userAccount.getAccountId();
            String contactPerson = isHaveContactPerson(contactInformation, followSource, callId, accountId);
            if (contactPerson != null){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contactPerson);
            }
            //如果电话前面有0，去掉0再查一下
            if (contactInformation.startsWith("0")) {
                contactInformation = contactInformation.substring(1,contactInformation.length());
                String contactPerson0 = isHaveContactPerson(contactInformation, followSource, callId, accountId);
                if (contactPerson0 != null){
                    return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contactPerson0);
                }
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("callManager isContactExist error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 判断是否有联系人,并返回联系人姓名
     * @Author pym
     * @Date  2021/7/7 14:10
     * @param contactInformation 联系电话
     * @param followSource 跟进来源：0-线索跟进；1-客户跟进；2-单品客户跟进;
     * @param callId 单品客户Id/线索Id
     * @param accountId 账号Id
     * @return {@link {boolean}}
     */
    private String isHaveContactPerson(String contactInformation, String followSource,  String callId, String accountId) {
        if ("2".equals(followSource) || "0".equals(followSource)) {
            if (StringUtils.isNotBlank(callId)) {
                if ("2".equals(followSource)) {
                    SingleProductCustomerContact singleProductCustomerContact
                            = singleProductCustomerService.getSingleProductCustomerContactById(callId, contactInformation, accountId);
                    if (singleProductCustomerContact != null) {
                        return singleProductCustomerContact.getContactName();
                    }
                } else if ("0".equals(followSource)) {
                    ClueContact clueContact = clueContactService.getClueContactByIdAndContactInfo(callId, contactInformation);
                    if (clueContact != null) {
                        return clueContact.getContactName();
                    }
                }
            }
        } else {
            //Contact contact = contactService.getContactByContactInfoAndId(contactInformation, accountId);
            ContactInformationVO contact = contactInformationService.getContactInformationByContactInfoAndId(contactInformation, accountId);
            if (contact != null) {
                return contact.getContactName();
            }
        }
        return null;
    }
}
